package com.superhelper.printer.server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.superhelper.printer.server.event.EventDispater;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

@Component
@Scope("prototype")
@Sharable
public class PrinterServerReader extends ChannelInboundHandlerAdapter { // (1)

    private static ExecutorService es = Executors.newCachedThreadPool();

    @Autowired
    private EventDispater eventDispater;

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) { // (2)
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                final ByteBuf buf = in.readBytes(in.readableBytes());
                // String content = buf.toString(CharsetUtil.UTF_8);
                es.submit(new Runnable() {
                    @Override
                    public void run() {
                        eventDispater.dispatch(buf, ctx);
                    }
                });
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        cause.printStackTrace();
        ctx.close();
    }
}